package com.rmfyzxfw.caseprocess.manager.redisson.config;

import lombok.extern.slf4j.Slf4j;
import okio.BufferedSource;
import okio.Okio;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * redisson配置类
 * @author Gyy
 * @date 2022-09-20
 */
@Slf4j
@Configuration
public class RedissonConfig {

    @Value("${redisson.address:}")
    private String address;
    @Value("${redisson.password:}")
    private String password;
    @Value("${redisson.database:}")
    private int database;

    private static final String FILE_NAME_TEMPLATE = "redisson_config.yml";

    @Bean
    public RedissonClient redissonClient() {
        Config config = getRedissonConfig();
        config.setCodec(new FastJsonCodec());
        config.useSingleServer().setAddress(address).setPassword(password).setDatabase(database);
        return Redisson.create(config);
    }

    private Config getRedissonConfig() {
        Resource resource = getResource();
        if (Objects.isNull(resource)) {
            log.error("未找到redisson配置");
        }
        String content = null;
        try (InputStream inputStream = resource.getInputStream();
             BufferedSource buffer = Okio.buffer(Okio.source(inputStream))) {
            content = buffer.readString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("加载redisson配置文件失败!", e);
        }
        try {
            return Config.fromYAML(content);
        } catch (IOException e) {
            log.error("组装redisson配置文件错误!", e);
        }
        return null;
    }

    private Resource getResource() {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = getResource(FILE_NAME_TEMPLATE, resolver);
        return resource;
    }

    private Resource getResource(String fileName, ResourcePatternResolver resolver) {
        String filePath = "file:." + File.separator + fileName;
        Resource resource = resolver.getResource(filePath);
        if (resource.exists()) {
            return resource;
        }
        filePath = fileName;
        resource = resolver.getResource(filePath);
        if (resource.exists()) {
            return resource;
        }
        return null;
    }
}
